package com.earl.mbasystem.domain.user;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.earl.mbasystem.domain.base.BaseDaoImpl;
import com.earl.mbasystem.domain.userrolemapping.UserRoleManagePo;


/**
 * 
 * 
 */
@Repository("userDao")
public class UserDaoImpl extends BaseDaoImpl<UserPo> implements UserDao {

	private static UserDao userDao;
	
	public UserDaoImpl(){
		System.out.println("");
	}
	
	@Resource(name = "userDao")
	UserDao m;
	
	@PostConstruct
	public void init(){
		userDao = m;
	}
	
	
	@Override
	public UserPo getByName(String username) {
		// TODO 未测试.
		String hql= "from UserPo where employeeName =:employeeName";
		UserPo user = (UserPo) getCurrentSession().createQuery(hql).setString("employeeName", username).uniqueResult();
		return user;
	}

	@Override
	public List<String> getPrivilegeName(Long userId) {
		// TODO 未测试.
		
		String hql = "select p.privilegeName from user u  " +
					 "left outer join useRroleManage ur on u.userId=ur.userId "+
					 "left outer join role r on r.roleId = ur.roleId "+
					 "left outer join roleprivilegemanage rp on r.roleId=rp.roleId "+
					 "left outer join privilege p on rp.privilegeId=p.privilegeId "+
					 "where u.userId=:userId ";
		@SuppressWarnings("unchecked")
		List<String> list = getCurrentSession().createSQLQuery(hql).setLong("userId", userId).list();
		return list;
	}

	@Override
	public List<String> getRolesName(Long userId) {
		// TODO 未测试.
		String hql = "select r.roleName from user u  " +
				 "left outer join useRroleManage ur on u.userId=ur.userId "+
				 "left outer join role r on r.roleId = ur.roleId "+
				 "where u.userId=:userId ";
		@SuppressWarnings("unchecked")
		List<String> list = getCurrentSession().createSQLQuery(hql).setLong("userId", userId).list();
		return list;
	}


	public static UserDao getInstance() {
		// TODO 未测试.
		return userDao;
	}

	
	@Override
	public void updateUser(UserPo model, Long[] roleId) {
		// TODO 未测试.
		String sql = "delete from UserRoleManagePo where userId =:user";
		getCurrentSession().createQuery(sql).setLong("user", model.getUserId()).executeUpdate();
		for (Long long1 : roleId) {
			UserRoleManagePo ur = new UserRoleManagePo();
			ur.setUserId(model.getUserId());
			ur.setRoleId(long1);
			getCurrentSession().save(ur);
		}
	}


	@Override
	public List<String> getPrivilegeUrl(Long userId) {
		
		String hql = "select p.url from user u  " +
				 "left outer join useRroleManage ur on u.userId=ur.userId "+
				 "left outer join role r on r.roleId = ur.roleId "+
				 "left outer join roleprivilegemanage rp on r.roleId=rp.roleId "+
				 "left outer join privilege p on rp.privilegeId=p.privilegeId "+
				 "where u.userId=:userId ";
			@SuppressWarnings("unchecked")
	List<String> list = getCurrentSession().createSQLQuery(hql).setLong("userId", userId).list();
	return list;
	}
}